package message

import (
	"context"
	"fmt"
	"gosync/config"
	"log/slog"
	"os"
	"time"

	"github.com/natefinch/lumberjack"
)

type ctxKey string

var LogMsg *slog.Logger

const (
	slogFields ctxKey = "crontab_request_id"
)

type ContextHandler struct {
	slog.Handler
}

func init() {

	logFile := &lumberjack.Logger{
		Filename:   config.SyncConfig.LogPath + "sync.log", // 日志文件路径
		MaxSize:    50,                                     // 每个日志文件的最大尺寸，单位是MB
		MaxBackups: 30,                                     // 保留旧日志文件的最大数量
		MaxAge:     28,                                     // 保留旧日志文件的最大天数
		Compress:   false,                                  // 是否压缩旧日志文件
	}

	h := &ContextHandler{slog.NewJSONHandler(logFile, nil)}
	LogMsg = slog.New(h)

}

func InfoFile(fileName string) *slog.Logger {
	f, err := os.OpenFile(config.SyncConfig.LogPath+fileName+".log", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
	if err != nil {
		panic(err)
	}

	h := &ContextHandler{slog.NewJSONHandler(f, nil)}
	return slog.New(h)
}

// Handle adds contextual attributes to the Record before calling the underlying
// handler
func (h ContextHandler) Handle(ctx context.Context, r slog.Record) error {
	if attrs, ok := ctx.Value(slogFields).([]slog.Attr); ok {
		for _, v := range attrs {
			r.AddAttrs(v)
		}
	}
	return h.Handler.Handle(ctx, r)
}

// AppendCtx adds an slog attribute to the provided context so that it will be
// included in any Record created with such context
func AppendCtx(parent context.Context, attr slog.Attr) context.Context {
	if parent == nil {
		parent = context.Background()
	}
	if v, ok := parent.Value(slogFields).([]slog.Attr); ok {
		v = append(v, attr)
		return context.WithValue(parent, slogFields, v)
	}
	v := []slog.Attr{}
	v = append(v, attr)
	return context.WithValue(parent, slogFields, v)
}

func getLogFileName() string {
	// 使用当前日期生成日志文件名
	t := time.Now()
	return fmt.Sprintf(config.SyncConfig.LogPath+"sync-%s.log", t.Format("2006-01-02-15-04-05"))
}
